package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.mapper.ClientMapper;
import org.example.pojo.Article;
import org.example.pojo.Client;
import org.example.pojo.PageBean;
import org.example.service.ClientService;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ClientServiceImpl implements ClientService {

    @Autowired
    private ClientMapper clientMapper;

    @Override
    public PageBean<Client> list(Integer pageNum, Integer pageSize, String state){
        //1.创建PageBean对象
        PageBean<Client> pageBean = new PageBean<>();
        //2.开启分页查询PageHelper
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Client> as = clientMapper.list(userId,state);
        Page<Client> pageInfo = (Page<Client>) as;

        pageBean.setTotal(pageInfo.getTotal());
        pageBean.setItems(pageInfo.getResult());

        return pageBean;
    }

    @Override
    public void add(Client client) {
        //设置时间
        client.setCreateTime(LocalDateTime.now());
        client.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        client.setCreateUser(id);

        clientMapper.add(client);
    }

    @Override
    public void update(Client client) {
        client.setUpdateTime(LocalDateTime.now());
        clientMapper.update(client);
    }

    @Override
    public void delete(Integer id) {
        clientMapper.delete(id);
    }

    @Override
    public Client getById(Integer id) {
        return clientMapper.getById(id);
    }

    @Override
    public List<Client> getAll() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        return clientMapper.getAll(id);
    }

    @Override
    public List<Client> getClientByName(String name) {
        return clientMapper.getClientByName(name);
    }
}
